<template>
  <el-dialog
    v-model="visible"
    title="住户关系管理"
    width="800px"
    @close="handleClose"
  >
    <div class="relation-container" v-loading="loading">
      <div class="current-resident">
        <h4>当前住户：{{ currentResidentName }}</h4>
      </div>
      
      <!-- 现有关系列表 -->
      <div class="existing-relations">
        <div class="section-header">
          <h4>现有关系</h4>
          <el-button type="primary" size="small" @click="handleAddRelation">
            <el-icon><Plus /></el-icon>
            添加关系
          </el-button>
        </div>
        
        <el-table :data="relationList" border stripe>
          <el-table-column prop="relatedResidentName" label="关联住户" />
          <el-table-column prop="relationType" label="关系类型">
            <template #default="{ row }">
              {{ getRelationTypeText(row.relationType) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="danger" size="small" text @click="handleDeleteRelation(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-if="relationList.length === 0" description="暂无关系数据" />
      </div>
      
      <!-- 添加关系表单 -->
      <el-dialog
        v-model="addRelationVisible"
        title="添加住户关系"
        width="500px"
        append-to-body
      >
        <el-form
          ref="relationFormRef"
          :model="relationForm"
          :rules="relationFormRules"
          label-width="100px"
        >
          <el-form-item label="关联住户" prop="relatedResidentId">
            <el-select
              v-model="relationForm.relatedResidentId"
              placeholder="请选择关联住户"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="resident in availableResidents"
                :key="resident.id"
                :label="resident.name"
                :value="resident.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="关系类型" prop="relationType">
            <el-select v-model="relationForm.relationType" placeholder="请选择关系类型" style="width: 100%">
              <el-option label="夫妻" :value="1" />
              <el-option label="父子" :value="2" />
              <el-option label="母子" :value="3" />
              <el-option label="兄弟" :value="4" />
              <el-option label="姐妹" :value="5" />
              <el-option label="其他" :value="6" />
            </el-select>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="addRelationVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRelation" :loading="submitting">
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 住户关系管理组件
 * @author Wu.Liang
 * @date 2025-07-28
 */
import { ref, reactive, computed, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { residentApi } from '@/api/resident'
import { showMessage } from '@/utils/message'

// 定义props
interface Props {
  visible: boolean
  residentId: number
  householdId: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  residentId: 0,
  householdId: 0
})

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

// 响应式数据
const loading = ref(false)
const addRelationVisible = ref(false)
const submitting = ref(false)
const relationFormRef = ref<FormInstance>()
const currentResidentName = ref('')
const relationList = ref<any[]>([])
const availableResidents = ref<any[]>([])

// 关系表单数据
const relationForm = reactive({
  relatedResidentId: undefined as number | undefined,
  relationType: undefined as number | undefined
})

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 关系类型映射
const relationTypeMap = {
  1: '夫妻',
  2: '父子',
  3: '母子',
  4: '兄弟',
  5: '姐妹',
  6: '其他'
}

// 表单验证规则
const relationFormRules: FormRules = {
  relatedResidentId: [
    { required: true, message: '请选择关联住户', trigger: 'change' }
  ],
  relationType: [
    { required: true, message: '请选择关系类型', trigger: 'change' }
  ]
}

// 获取关系类型文本
const getRelationTypeText = (type: number) => {
  return relationTypeMap[type as keyof typeof relationTypeMap] || '未知'
}

// 加载住户关系
const loadResidentRelations = async () => {
  if (!props.residentId) return
  
  try {
    loading.value = true
    const response = await residentApi.getResidentRelations(props.residentId)
    relationList.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    showMessage({ type: 'error', message: '加载住户关系失败' })
    relationList.value = []
  } finally {
    loading.value = false
  }
}

// 加载可用住户列表
const loadAvailableResidents = async () => {
  if (!props.householdId) return
  
  try {
    const response = await residentApi.getResidentList({ householdId: props.householdId })
    const residents = Array.isArray(response.data?.records) ? response.data.records : []
    // 过滤掉当前住户
    availableResidents.value = residents.filter(resident => resident.id !== props.residentId)
  } catch (error) {
    showMessage({ type: 'error', message: '加载住户列表失败' })
    availableResidents.value = []
  }
}

// 加载当前住户信息
const loadCurrentResident = async () => {
  if (!props.residentId) return
  
  try {
    const response = await residentApi.getResidentById(props.residentId)
    currentResidentName.value = response.data.name
  } catch (error) {
    console.error('加载当前住户信息失败:', error)
    currentResidentName.value = '未知住户'
  }
}

// 添加关系
const handleAddRelation = () => {
  relationForm.relatedResidentId = undefined
  relationForm.relationType = undefined
  addRelationVisible.value = true
}

// 提交关系
const handleSubmitRelation = async () => {
  if (!relationFormRef.value) return
  
  try {
    await relationFormRef.value.validate()
    submitting.value = true
    
    const submitData = {
      residentId: props.residentId,
      relatedResidentId: relationForm.relatedResidentId,
      relationType: relationForm.relationType
    }
    
    await residentApi.addResidentRelation(submitData)
    showMessage({ type: 'success', message: '添加关系成功' })
    
    addRelationVisible.value = false
    loadResidentRelations()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '添加关系失败' })
    }
  } finally {
    submitting.value = false
  }
}

// 删除关系
const handleDeleteRelation = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除与"${row.relatedResidentName}"的关系吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await residentApi.deleteResidentRelation(row.id)
    showMessage({ type: 'success', message: '删除关系成功' })
    loadResidentRelations()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除关系失败' })
    }
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  addRelationVisible.value = false
  relationList.value = []
  currentResidentName.value = ''
}

// 监听visible变化
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.residentId) {
    loadCurrentResident()
    loadResidentRelations()
    loadAvailableResidents()
  }
})
</script>

<style scoped>
.relation-container {
  padding: 20px;
}

.current-resident {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.current-resident h4 {
  margin: 0;
  color: #409eff;
}

.existing-relations {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
}
</style> 